using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Application.Dtos;
using TenantManagementService.Tenants;
using TenantManagementService.Monitoring;

namespace TenantManagementService.Controllers
{
    /// <summary>
    /// 租户续期管理控制器
    /// </summary>
    [ApiController]
    [Route("api/tenant-renewal")]
    public class TenantRenewalController : AbpControllerBase
    {
        private readonly TenantRenewalService _tenantRenewalService;
        private readonly ITenantAppService _tenantAppService;
        private readonly IRepository<TenantConfiguration, Guid> _tenantConfigurationRepository;

        public TenantRenewalController(
            TenantRenewalService tenantRenewalService,
            ITenantAppService tenantAppService,
            IRepository<TenantConfiguration, Guid> tenantConfigurationRepository)
        {
            _tenantRenewalService = tenantRenewalService;
            _tenantAppService = tenantAppService;
            _tenantConfigurationRepository = tenantConfigurationRepository;
        }

        /// <summary>
        /// 手动触发续期检查
        /// </summary>
        [HttpPost("check-renewals")]
        public async Task<IActionResult> CheckRenewalsAsync()
        {
            try
            {
                var result = await _tenantRenewalService.TriggerRenewalCheckAsync();

                return Ok(new
                {
                    success = true,
                    data = result,
                    message = "续期检查完成"
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }

        /// <summary>
        /// 续期指定租户
        /// </summary>
        [HttpPost("{tenantId}/renew")]
        public async Task<IActionResult> RenewTenantAsync(
            Guid tenantId,
            [FromBody] RenewTenantRequest request)
        {
            try
            {
                var renewalPeriod = request.RenewalPeriod ?? TimeSpan.FromDays(30);
                var result = await _tenantRenewalService.RenewTenantAsync(tenantId, renewalPeriod);

                if (result.IsSuccess)
                {
                    return Ok(new
                    {
                        success = true,
                        message = "租户续期成功",
                        details = result.Message
                    });
                }
                else
                {
                    return BadRequest(new
                    {
                        success = false,
                        message = "租户续期失败",
                        details = result.Message
                    });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }

        /// <summary>
        /// 批量续期租户
        /// </summary>
        [HttpPost("batch-renew")]
        public async Task<IActionResult> BatchRenewTenantsAsync([FromBody] BatchRenewRequest request)
        {
            try
            {
                var results = new List<object>();

                foreach (var tenantId in request.TenantIds)
                {
                    var renewalPeriod = request.RenewalPeriod ?? TimeSpan.FromDays(30);
                    var result = await _tenantRenewalService.RenewTenantAsync(tenantId, renewalPeriod);

                    results.Add(new
                    {
                        tenantId = tenantId,
                        success = result.IsSuccess,
                        message = result.Message
                    });
                }

                var successCount = results.Count(r => ((dynamic)r).success);

                return Ok(new
                {
                    success = true,
                    total_count = request.TenantIds.Count,
                    success_count = successCount,
                    failed_count = request.TenantIds.Count - successCount,
                    results = results
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取租户的自动续期配置
        /// </summary>
        [HttpGet("{tenantId}/auto-renewal-config")]
        public async Task<IActionResult> GetAutoRenewalConfigAsync(Guid tenantId)
        {
            try
            {
                var queryable = await _tenantConfigurationRepository.GetQueryableAsync();
                var config = await AsyncExecuter.FirstOrDefaultAsync(
                    queryable.Where(c => c.TenantId == tenantId && c.Key == "auto_renewal"));

                if (config?.Value == null)
                {
                    return Ok(new
                    {
                        success = true,
                        data = new AutoRenewalConfiguration
                        {
                            Enabled = false,
                            RenewalPeriod = TimeSpan.FromDays(30),
                            MaxAutoRenewalCount = 12,
                            RenewalWarningDays = 7,
                            NotifyOnRenewal = true,
                            NotifyOnExpiration = true
                        }
                    });
                }

                var autoRenewalConfig = System.Text.Json.JsonSerializer.Deserialize<AutoRenewalConfiguration>(config.Value);

                return Ok(new
                {
                    success = true,
                    data = autoRenewalConfig
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }

        /// <summary>
        /// 设置租户的自动续期配置
        /// </summary>
        [HttpPost("{tenantId}/auto-renewal-config")]
        public async Task<IActionResult> SetAutoRenewalConfigAsync(
            Guid tenantId,
            [FromBody] AutoRenewalConfiguration config)
        {
            try
            {
                var configJson = System.Text.Json.JsonSerializer.Serialize(config);

                var queryable = await _tenantConfigurationRepository.GetQueryableAsync();
                var existingConfig = await AsyncExecuter.FirstOrDefaultAsync(
                    queryable.Where(c => c.TenantId == tenantId && c.Key == "auto_renewal"));

                if (existingConfig != null)
                {
                    existingConfig.ChangeValue(configJson);
                    await _tenantConfigurationRepository.UpdateAsync(existingConfig, autoSave: true);
                }
                else
                {
                    var newConfig = new TenantConfiguration(
                        Guid.NewGuid(),
                        tenantId,
                        "auto_renewal",
                        configJson,
                        "续期配置",
                        "Auto renewal settings"
                    );
                    await _tenantConfigurationRepository.InsertAsync(newConfig, autoSave: true);
                }

                return Ok(new
                {
                    success = true,
                    message = "自动续期配置已更新"
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取即将过期的租户列表
        /// </summary>
        [HttpGet("expiring-soon")]
        public async Task<IActionResult> GetExpiringSoonTenantsAsync([FromQuery] int days = 7)
        {
            try
            {
                var tenants = await _tenantAppService.GetExpiringSoonTenantsAsync(days);

                return Ok(new
                {
                    success = true,
                    data = tenants,
                    days = days,
                    count = tenants.Items?.Count ?? 0
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取过期租户列表
        /// </summary>
        [HttpGet("expired")]
        public async Task<IActionResult> GetExpiredTenantsAsync([FromQuery] GetExpiredTenantsInput input)
        {
            try
            {
                var tenants = await _tenantAppService.GetExpiredTenantsAsync(input);

                return Ok(new
                {
                    success = true,
                    data = tenants
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取续期统计信息
        /// </summary>
        [HttpGet("statistics")]
        public async Task<IActionResult> GetRenewalStatisticsAsync()
        {
            try
            {
                var statistics = await _tenantAppService.GetRenewalStatisticsAsync();

                return Ok(new
                {
                    success = true,
                    data = statistics
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }
    }

    /// <summary>
    /// 续期租户请求
    /// </summary>
    public class RenewTenantRequest
    {
        /// <summary>
        /// 续期时长
        /// </summary>
        public TimeSpan? RenewalPeriod { get; set; }

        /// <summary>
        /// 续期原因
        /// </summary>
        public string? Reason { get; set; }
    }

    /// <summary>
    /// 批量续期请求
    /// </summary>
    public class BatchRenewRequest
    {
        /// <summary>
        /// 租户ID列表
        /// </summary>
        public List<Guid> TenantIds { get; set; } = new();

        /// <summary>
        /// 续期时长
        /// </summary>
        public TimeSpan? RenewalPeriod { get; set; }

        /// <summary>
        /// 续期原因
        /// </summary>
        public string? Reason { get; set; }
    }

    /// <summary>
    /// 获取过期租户输入
    /// </summary>
    public class GetExpiredTenantsInput : PagedAndSortedResultRequestDto
    {
        /// <summary>
        /// 过期天数筛选
        /// </summary>
        public int? ExpiredDays { get; set; }

        /// <summary>
        /// 租户类型筛选
        /// </summary>
        public TenantType? TenantType { get; set; }
    }
}